package com.lsmo.android.carfans.activity.car;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

import com.lsmo.android.carfans.R;
import com.lsmo.android.carfans.model.car.Brand;
import com.lsmo.android.util.Caller;
import com.lsmo.android.util.json.JSONException;
import com.lsmo.android.util.json.JSONUtils;

/**
 * 车型中按照品牌和价格选择
 * @author SYX
 *
 */
public class SelectCarAcitivity extends ListActivity 
	implements AdapterView.OnItemClickListener, View.OnClickListener{
	
	public static String TAG = "SelectCarActivity";
	ArrayList<Brand> BrandList;
	private Button button01,button02;
	private int flag;
	private ListView listView;
	private String[] strs;
	
    private RemoveWindow mRemoveWindow = new RemoveWindow();
	Handler mHandler = new Handler();
    private WindowManager mWindowManager;
	private TextView mDialogText;
	private boolean mShowing;
	private boolean mReady;
	private char mPrevLetter = Character.MIN_VALUE;
	public String[] mStrings;
	
	public List mLists;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		scrollView();//listview
		initView();//加载view
		
//	    setBrandView();//品牌
		setPrice();//价格
	}

	/**
	 * 获取车型数据
	 */
	public void downloadData()
	{
		try {
			String str = Caller.convertStreamToString(getResources().getAssets().open("brand"));
			Log.i(TAG,"str==" + str);
			try {
				BrandList =new BrandParser(str).Paser2Object();
			} catch (Exception e) {
				e.printStackTrace();
			}
			Log.i(TAG,"BrandList==" + BrandList);
		} catch (IOException e) {
			e.printStackTrace();
		}
	    
	}
	
	public void initView()
	{
		downloadData();//加载数据
		setContentView(R.layout.car_main_selectcar_layout);
		button01 = (Button)findViewById(R.id.select_button01);//按品牌
	    button01.setOnClickListener(this);
	    
	    button02 = (Button)findViewById(R.id.select_button02);//按价格
	    button02.setOnClickListener(this);
	    
	    listView = getListView();
	}
	
	/**
	 * listview滚动view
	 */
	public void scrollView(){
		getStrings();//将json转换成String[]
		mWindowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
		
		LayoutInflater inflate = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mDialogText = (TextView) inflate.inflate(R.layout.car_list_position, null);
        mDialogText.setVisibility(View.INVISIBLE);
        
        mHandler.post(new Runnable() {
            public void run() {
                mReady = true;
                WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                        WindowManager.LayoutParams.TYPE_APPLICATION,
                        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                        PixelFormat.TRANSLUCENT);
                mWindowManager.addView(mDialogText, lp);
            }});
	}
	
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, 
			int arg2, long arg3) {
	}
	
	/**
	 * listview滚动监听事件
	 */
    public OnScrollListener scrollListener = new OnScrollListener() {
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}
		
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			int lastItem = firstVisibleItem + visibleItemCount - 1;
	        if (mReady) {
	        	char firstLetter = mStrings[firstVisibleItem+3].charAt(0);
	            
	            if (!mShowing && firstLetter != mPrevLetter) {
	                mShowing = true;
	                mDialogText.setVisibility(View.VISIBLE);
	            }
	            mDialogText.setText(((Character)firstLetter).toString());
	            mHandler.removeCallbacks(mRemoveWindow);
	            mHandler.postDelayed(mRemoveWindow, 3000);
	            mPrevLetter = firstLetter;
	        }
		}
	};
	
	/**
	 * tab按钮监听
	 */
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		//按品牌
		case R.id.select_button01:
			setBrandView();//品牌
			break;
	    //按价格
		case R.id.select_button02:
			setPrice();//价格
			break;
		}
	}
	
	//品牌
	public void setBrandView()
	{
		if (BrandList == null){
			downloadData();
		}
		else if((BrandList != null) && (BrandList.size() > 0)){
			BrandAdapter localBrandAdapter = new BrandAdapter(this);
		    localBrandAdapter.setList(BrandList);
		    
		    // separate adapters on one list
//			SeparatedListAdapter separatedAdapter = new SeparatedListAdapter(this); 
//			Map mapinfo = (Map) BrandList.get(0);
//			String titleString = (String)mapinfo.get("FirstLetter");
//			separatedAdapter.addSection(titleString.toUpperCase(), localBrandAdapter);
			
		    localBrandAdapter.setListView(this.listView);
		    listView.setAdapter(localBrandAdapter);
		    listView.setOnItemClickListener(this);//监听事件
		    listView.setOnScrollListener(scrollListener);//给ListView注册滚动监听
		}
		flag = 0;
		button01.setBackgroundResource(R.drawable.navigation_button_bg);
		button02.setBackgroundResource(R.drawable.transparent);
	}
	
	//价格
	public void setPrice()
	{
		String[] arrayOfString1 = getResources()
					.getStringArray(R.array.select_by_price_array);
	    strs = arrayOfString1;
	    String[] arrayOfString2 = strs;
	    ArrayAdapter localArrayAdapter = new ArrayAdapter(this, 
	    		R.layout.car_adapter_price, R.id.price_text, arrayOfString2);
	    listView.setAdapter(localArrayAdapter);
	    flag = 1;
	    button02.setBackgroundResource(R.drawable.navigation_button_bg);
	    button01.setBackgroundResource(R.drawable.transparent);
	}
	
	
	/**
	 * 滑动窗体类
	 * @author SYX
	 */
	private final class RemoveWindow implements Runnable {
        public void run() {
            removeWindow();
        }
    }
	/**
	 * 滑动窗体方法
	 */
    private void removeWindow() {
        if (mShowing) {
            mShowing = false;
            mDialogText.setVisibility(View.INVISIBLE);
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        mReady = true;
    }

    
    @Override
    protected void onPause() {
        super.onPause();
        removeWindow();
        mReady = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWindowManager.removeView(mDialogText);
        mReady = false;
    }
    
    /**
     * 将json转换成String[]
     * @return
     */
    public String[] getStrings(){
    	mLists = new ArrayList<Map<String, Object>>();
    	try {
    		//获取数据源
			String str2 = Caller.convertStreamToString(getResources().getAssets().open("brand"));
			try {
				List<Map> list = (ArrayList<Map>)JSONUtils.deserialize(str2);
				for(Map mapList:list){
					String firstLetter = mapList.get("FirstLetter")==null?"":mapList.get("FirstLetter").toString();//首字母
					mLists.add(firstLetter.toUpperCase());
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		mStrings = new String[mLists.size()];
		for(int i= 0;i<mLists.size();i++){ 
			  mStrings[i] = mLists.get(i).toString();
			  Log.i(TAG, "字母数组：" + mStrings[i]);
		}
		return mStrings;
    }
}
